#!/usr/bin/python
import subprocess
import shutil
from pathlib import Path
import logging
import time
import sys

BUILD_DIR = Path('build')
COMMAND_LOGGER = logging.getLogger('build.command')
if not COMMAND_LOGGER.handlers:
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(logging.Formatter('%(message)s'))
    handler.terminator = ''
    COMMAND_LOGGER.addHandler(handler)
COMMAND_LOGGER.propagate = False
COMMAND_LOGGER.setLevel(logging.INFO)

def rm_build():
    if BUILD_DIR.exists():
        shutil.rmtree(BUILD_DIR)

def run_command(cmd, cwd=None, check=True):
    """Run command and keep carriage-return heavy output readable."""
    process = subprocess.Popen(
        cmd,
        cwd=cwd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        bufsize=1,
        universal_newlines=True,
    )
    if process.stdout is None:
        raise RuntimeError('stdout pipe was not created')
    try:
        for chunk in process.stdout:
            COMMAND_LOGGER.info(chunk)
    finally:
        process.stdout.close()
    retcode = process.wait()
    if check and retcode != 0:
        raise subprocess.CalledProcessError(retcode, cmd)
    return retcode


def build():
    BUILD_DIR.mkdir(parents=True, exist_ok=True)
    run_command(['cmake', '-G', 'Unix Makefiles', '..'], cwd=BUILD_DIR)
    run_command(['make', 'clean'], cwd=BUILD_DIR, check=False)
    run_command(['make', '-j8'], cwd=BUILD_DIR)

def copy_exe_file():
    source = BUILD_DIR / 'checksum.exe'
    target = Path('output/checksum.exe')
    target.parent.mkdir(parents=True, exist_ok=True)

    try:
       shutil.copyfile(source, target)
    except Exception as e:
       logging.error("Unable to copy file. %s", e)

def checksum_hex_file():
    # 优化参数配置，确保在Windows环境下输出直接显示在终端上
    exe_path = Path('output') / 'checksum.exe'
    run_command([str(exe_path), 'WSA319.hex', 'ALL'],
                cwd=exe_path.parent)

def main():
    start = time.perf_counter()

    rm_build()
    build()
    copy_exe_file()
    checksum_hex_file()

    end = time.perf_counter()
    logging.info('run time: %s second', end - start)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    main()
